package com.ocl.www.controller;

import com.ocl.www.domain.MyCollection;
import com.ocl.www.service.MyCollectionService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by Administrator on 2016/11/7.
 */
@RestController
@RequestMapping("/mycollection")
public class MyCollectionController {

    @Autowired
    private MyCollectionService myCollectionService;

    private Logger log = Logger.getLogger(MyCollectionController.class);


    @ResponseBody
    @RequestMapping(value = "/insertMyCollection",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="添加收藏", notes="添加收藏，如果已收藏则删除收藏(post方式)",httpMethod = "POST")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{articleId:29}", required = true, dataType = "Map")
    public Map<String,Object> insertMyCollection(@RequestBody Map<String,Object> maptemp){

        MyCollection myCollection = new MyCollection();
        myCollection.setArticleId(maptemp.get("articleId").toString());

        Set<?> s = SecurityUtils.getSubject().getPrincipals().asSet();
        Object[] obj = new Object[2];
        int obji = 0;
        Iterator<?> it = s.iterator();
        while(it.hasNext()){
            obj[obji] = it.next();
            log.info(obj.getClass());
            log.info(obj.toString());
            obji++;
        }
        Map<String,String> map = (Map<String, String>) obj[1];

        String userId = map.get("userId").toString();
        myCollection.setUserId(userId);
        Date d = new Date();
        myCollection.setCreateTime(new Timestamp( d.getTime()));

        int c = 0;
        try {
            List<MyCollection> myCollectionList = myCollectionService.selectMyCollections(myCollection);
            if(myCollectionList.size() >= 1){
                c = myCollectionService.deleteMyCollection(myCollectionList.get(0));
                maptemp.put("info","e");
                maptemp.put("tip","already collection");
                return maptemp;
            }
            c = myCollectionService.insertMyCollection(myCollection);
            maptemp.put("info","s");
            maptemp.put("tip",c);
        } catch (Exception e) {
            e.printStackTrace();
            maptemp.put("info","e");
            maptemp.put("tip",e);
        }
        return maptemp;

    }


}
